<?php

namespace App\Logic\Order;

use App\Core\BaseCore;
use App\Core\BaseModel;
use App\Core\Exception\DefaultException;
use App\Core\Output;
use App\EventHandler\CountOrderTaskHandler;
use App\Logic\Order\Form\OrderTaskListForm;
use App\Model\Order\OrderModel;
use App\Model\Order\OrderTaskModel;
use App\Util\ArrayHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\Component\Singleton;
use EasySwoole\Http\Request;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\RedisPool\RedisPool;
use Throwable;

class OrderTaskService extends BaseCore
{

    use Singleton;

    /**
     * 订单相关字典项目 getDict
     * @return Output
     * @throws DefaultException
     * @throws Throwable
     */
    public function getDict($request): Output
    {

        return $this->success([
            'order_state'   => ArrayHelper::keyArrayToList(OrderModel::getOrderStateDict()),
        ]);
    }
    /**
     * 订单任务列表 getLists
     * @param Request $request
     * @return Output
     * @throws DefaultException
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\Redis\Exception\RedisException
     */
    public function getLists(Request $request){
        $params    = $request->getQueryParams();
        $cache     = RedisPool::defer();
        $cache_key = "orderTaskCache:lists:" . json_encode($params + ['_id' => UserIdentityHelper::getId(), '_name' => UserIdentityHelper::getUsername()]);
        if ($cache_data = $cache->get($cache_key)) { //缓存存在
            $data = json_decode($cache_data, true);
        } else {
            $form = new OrderTaskListForm($params, $request);
            $data = $form->lists();
            $cache->set($cache_key, json_encode($data), BaseModel::CACHE_EXPIRE);
        }
        return $this->success($data);
    }
    /**统计*/
    public function jobCount()
    {
        if((date('Hi') - 0) < 330){
            return false;
        }
        $table = OrderTaskModel::create()->getTableName();
        $limit = OrderTaskModel::COUNTLIMIT;
        $startDate = '2024-11-01';//date('Y-m-01');
        $lastUpdateTime = date('Y-m-d H:i:s', strtotime("-3 hours"));
        $sql = "SELECT * FROM {$table} WHERE created_at>'{$startDate}' AND updated_at<'{$lastUpdateTime}' AND quantity>finished_order_count LIMIT {$limit} ";

        $queryBuild = new QueryBuilder();
        $queryBuild->raw($sql);
        $result = DbManager::getInstance()->query($queryBuild, true);

        if ($result->getResult()) {
            foreach ($result->getResult() as $item){
                /** @var CountOrderTaskHandler eventCountOrderTask */
                \App\Process\LmtJob::getInstance()->createJob('eventCountOrderTask', ["id" => $item['id'], 'time' => time()]);
            }
        }
    }

    /**统计*/
    public function taskCount($id)
    {
        $task = OrderTaskModel::getOne(['id' => $id]);
        if (!$task) {
            return false;
        }
        $updateData = [
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => 'system'
        ];
        /**如果订单总金额为0,那么统计订单总金额*/
        if($task->order_amount == 0) {
            $where = [
                'task_id' => $id,
            ];
            $finAmount1 = OrderModel::create()->where($where)->sum('order_amount');
            $finAmount2 = OrderModel::create()->tableName(OrderModel::create()->getTableName() . '_returned')->where($where)->count('order_amount');
            $task->order_amount = bcadd($finAmount1, $finAmount2, 2);
            $updateData['order_amount'] = $task->order_amount;
        }

        /**如果单个提成为0,那么更新数据*/
        if($task->user_profit == 0) {
            $order1 = OrderModel::getOne($where);
            if(empty($order1)){
                $order2 = OrderModel::create()->tableName(OrderModel::create()->getTableName() . '_returned')->where($where)->get();
                if(!empty($order2)){
                    $user_profit = $order2->user_profit;
                }else{
                    $user_profit = 0;
                }
            }else{
                $user_profit = $order1->user_profit;
            }
            $task->user_profit = $user_profit;
            $updateData['user_profit'] = $task->user_profit;
        }


        /**  统计完成数量
        SELECT COUNT(1) FROM ss_order WHERE task_id=8508 AND order_state!='RETURNED';
        SELECT COUNT(1) FROM ss_order_returned WHERE task_id=8508 AND order_state='RETURNED';
        */
        $where = [
            'task_id' => $id,
            'order_state' => 'RETURNED'
        ];
        $finCount1 = OrderModel::create()->where($where)->count('id');
        $finCount2 = OrderModel::create()->tableName(OrderModel::create()->getTableName() . '_returned')->where($where)->count('id');
        /**取出上个月
        $prevMonth = date('Ym', strtotime(date('Y-m-01', strtotime($task['created_at']))) - 86400);
        $finCount3 = OrderModel::create()->tableName(OrderModel::create()->getTableName() . '_' . $prevMonth)->where($where)->count('id');
         */
        /**下单月*/
        $orderMonth = date('Ym', strtotime($task['created_at']));
        if(date('Ym') > $orderMonth){
            $finCount3 = OrderModel::create()->tableName(OrderModel::create()->getTableName() . '_' . $orderMonth)->where($where)->count('id');
        }else{
            $finCount3 = 0;
        }
        /**下单月下一个月*/
        $nextMonth = date('Ym', strtotime(date('Y-m-28', strtotime($task['created_at']))) + 86400 * 10);
        if(date('Ym') > $nextMonth){
            $finCount4 = OrderModel::create()->tableName(OrderModel::create()->getTableName() . '_' . $nextMonth)->where($where)->count('id');
        }else{
            $finCount4 = 0;
        }

        $count = $finCount1 + $finCount2 + $finCount3 + $finCount4;
        if($count > $task->finished_order_count) {
            $task->finished_order_count = $count;
            $task->total_user_profit = bcmul($task->finished_order_count, $task->user_profit, 2);
            $updateData['finished_order_count'] = $task->finished_order_count;
            $updateData['total_user_profit'] = $task->total_user_profit;
        }
        OrderTaskModel::updateData($updateData, ['id' => $id]);
        return true;
    }

}
